package com.apes.fn.server.productRequire;

import com.apes.fn.crm.customerExpand.FnCustomerExpand;
import com.apes.framework.api.SpringManager;
import com.apes.framework.jpa.DefaultPersistListener;
import com.apes.framework.jpa.Model;
import com.apes.framework.jpa.comment.Comment;
import com.apes.framework.jpa.generator.ApesGenerator;
import com.apes.framework.plugin.soe.annotations.State;
import com.apes.framework.plugin.soe.annotations.States;
import com.apes.framework.util.MapUtil;
import com.apes.scm.masterdata.frame.model.Channel;
import com.apes.scm.masterdata.frame.model.Dept;
import com.apes.scm.masterdata.frame.model.Store;
import com.apes.scm.masterdata.party.model.PartyRole;
import com.apes.scm.masterdata.party.repository.PartyRoleRepository;
import com.apes.scm.masterdata.product.model.ServeType;
import com.apes.scm.masterdata.stock.model.Location;
import lombok.Getter;
import lombok.Setter;
import org.hibernate.annotations.DynamicInsert;
import org.hibernate.annotations.DynamicUpdate;
import org.hibernate.annotations.SelectBeforeUpdate;

import javax.persistence.*;
import javax.validation.constraints.NotNull;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/***
 * 要货单
 */

@Getter
@Setter
@SelectBeforeUpdate
@DynamicInsert
@DynamicUpdate
@Entity
@EntityListeners(DefaultPersistListener.class)
@Table(name = ProductRequire.CONST_TABLE_NAME)
public class ProductRequire extends Model implements Cloneable{
    public static final String CONST_TABLE_NAME = "stock_product_require";

    @Id
    @Column(name = "id")
    @ApesGenerator(code = CONST_TABLE_NAME, name = "赋能要货单", prefix = "YH%(company)%(yy)%(month)", padding = 5, useDateRange=true)
    private String id; // 唯一编码

    @Column(name = "source", length = 30)
    @Comment("来源单号")
    private String source;

    @Column(name = "source_business_type", length = 32)
    @Comment("来源单据类型")
    private String sourceBusinessType;

    @Column(name = "source_business_type_name", length = 64)
    @Comment("来源单据类型名称")
    private String sourceBusinessTypeName;

    /***
     * 拼接数据用于前端展示
     */
    @Transient
    private String sourceType;

    public String getSourceType() {
        if (this.source != null && this.sourceBusinessTypeName != null) {
            return "[" + this.sourceBusinessTypeName + "]" + this.source;
        } else {
            return null;
        }
    }


    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "dept_id", referencedColumnName = "id")
    @Comment("采购组织编码")
    private Dept deptId;

    @NotNull
    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "location_id", referencedColumnName = "id")
    @Comment("库存位置")
    private Location location;

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "store_id", referencedColumnName="id")
    private Store store;


    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "company_id", referencedColumnName = "id", nullable = false)
    @Comment("公司")
    private PartyRole company;

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "serve_type_id", referencedColumnName = "id")
    @Comment("服务类型编码")
    private ServeType serveType;

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "channel_id", referencedColumnName = "id")
    @Comment("渠道编码")
    private Channel channel;

//    @Column(name = "vehicle_code", length = 16)
//    @Comment("车辆内码")
//    private String vehicleCode;

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "customer_expand_id", referencedColumnName = "id")
    @Comment("会员扩展表")
    private FnCustomerExpand customerExpand;

    @Transient
    private Map customer;

    public Map getCustomer() {
        if (customerExpand == null || customerExpand.getMobile() == null) return null;
        return MapUtil.mapper(
                "realname", customerExpand.getRealname(),
                "vendorCode", customerExpand.getVendorCode(),
                "mobile", customerExpand.getMobile()
        );
    }

    @Transient
    private Map customerCar;

    public Map getCustomerCar() {
        if (customerExpand == null || customerExpand.getCarLicense() == null) return null;
        return MapUtil.mapper(
                "carLicense", customerExpand.getCarLicense(),
                "vendorCode", customerExpand.getVendorCode(),
                "customer", this.getCustomer()
        );
    }

    @Column(name = "remark", length = 200)
    @Comment("备注")
    private String remark;

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "platform_id", referencedColumnName = "id", nullable = false)
    @Comment("平台")
    private PartyRole platform;

    @Column(name = "ZKXZBJ", columnDefinition = "number(2) default 0")
    @Comment("仓库选择标记(0:区域仓;1:总仓)")
    private int ZKXZBJ;

    @States(name = "状态", values = {
            @State(id = "create", name = "创建"),
            @State(id = "approve", name = "已审核"),
            @State(id = "delete", name = "删除"),
            @State(id = "repeal", name = "部分终止"),
            @State(id = "complete", name = "完成"),
            @State(id = "locked", name = "锁定"),
            @State(id = "dump", name = "要货单转储"),
    })
    @Column(name = "state")
    private String state;

    @Comment("创建时间")
    @Column(name = "create_date")
    private Date createDate;

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "approve_id", referencedColumnName = "id")
    @Comment("审核人")
    private PartyRole approveId; //审核

    @Comment("审批日期")
    @Column(name = "approve_date")
    private Date approveDate;

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "delete_id", referencedColumnName = "id")
    @Comment("删除人")
    private PartyRole deleteId; //删除

    @Column(name = "delete_date")
    @Comment("删除日期")
    private Date deleteDate; //删除日期

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "end_id", referencedColumnName = "id")
    @Comment("终止人")
    private PartyRole repealId;

    @Column(name = "end_date")
    @Comment("终止日期")
    private Date repealDate; //删除日期


    @Column(name = "require_arrive_date")
    @Comment("要求到货日期")
    private Date requireArriveDate;

    @Column(name = "interface_Push_Fail", length = 2000)
    @Comment("推送接口失败原因")
    private String interfacePushFail;

    @Column(name = "external_state", length = 24)
    @Comment("第三方—订单状态")//三头：{取消：cancel，发货：shipments}
    private String externalState;

    @OneToMany(mappedBy = "productRequire", cascade = CascadeType.ALL, orphanRemoval = true)
    private List<ProductRequireItem> productRequireItems = new ArrayList();


    public List<ProductRequireItem> getProductRequireItems() {
        int newQtyEndCount = 0;
        for (ProductRequireItem item : productRequireItems) {
            if (item.getQtyRequire() == 0) throw new RuntimeException("要货数量不能为 0 !");

            // 设置主表以及主表公司
            item.setProductRequire(this);
            item.setCompany(this.company);
            item.setDeptId(this.deptId);
            newQtyEndCount += item.getQtyEnd();
        }
        if (newQtyEndCount != 0 && this.qtyEndCount == 0) this.qtyEndCount = newQtyEndCount;
        return productRequireItems;
    }

    @Transient
    private PartyRole _creator;

    @Transient
    public PartyRole get_creator() {
        if (this.getCreator() == null) return null;
        return SpringManager.getBean(PartyRoleRepository.class).findOne(this.getCreator());
    }

    @Transient
    private PartyRole operator1;  //系统外的操作员

    @Transient
    private int qtyEndCount; // 统计每次终止统共多少隔

    @Transient
    private boolean writeBackQtyRequire = true; // 是否回写要货数量

    public int getQtyEndCount() {
        return this.qtyEndCount;
    }

    /***
     * 判断是否完成
     */
    public void checkComplete() {
        List<ProductRequireItem> item = this.getProductRequireItems();
        if( item.size() == 0 ) return;

        boolean isComplete = item.stream().noneMatch(productRequireItem ->
                productRequireItem.getQtyRequire() - productRequireItem.getQtyEnded() - productRequireItem.getQtyArrive() > 0);
        if (isComplete) this.setState("complete");
    }

    @Override
    protected Object clone() {
        ProductRequire productRequire = null;
        try {
            productRequire = (ProductRequire) super.clone();
        } catch (CloneNotSupportedException e) {
            e.printStackTrace();
        }
        return productRequire;
    }

}
